Skip to main content

index

Interceptors

Interceptors are a gRPC concept that allows apps to interact with incoming or outgoing gRPC calls by enriching the processing pipeline. These can be configured for a channel( named Client interceptors ) or service (Server interceptors), and are executed automatically for each gRPC call.

Interceptors are transparent to the user's application logic, being an excellent solution for common cases, such as logging, monitoring, authentication, and validation.

An interceptor allows you to do the following:

  • Update the original gRPC request before passing it along — for example, you might inject extra information such as auth headers
  • Manipulate the behavior of the original invoker function, such as bypassing the call so that you can use a cached result instead
  • Update the response before it’s returned to the client

Interceptors vs Middleware

Both Interceptors & Middleware

  • Are used to construct a pipeline that handles a gRPC request.
  • Allow work to be performed before or after the next component in the pipeline.
  • Provide access to HttpContext:
    • In middleware, the HttpContext is a parameter.
    • In interceptors, the HttpContext can be accessed using the ServerCallContext parameter with the ServerCallContext.GetHttpContext extension method.This feature is specific to interceptors running in ASP.NET Core.

Only Interceptors:

  • Operate on the gRPC layer of abstraction using the ServerCallContext. Provide access to:
  • The deserialized message sent to a call.
  • The message returned from the call before it's serialized.
  • Can catch and handle exceptions thrown from gRPC services.

Only Middleware:

  • Runs for all HTTP requests.
  • Runs before gRPC interceptors.
  • Operates on the underlying HTTP/2 messages.
  • Can only access bytes from the request and response stream

call flow

Writing an interceptor

To implement an interceptor( client or server), we need to inherit from the Interceptor class. This class doesn't do anything, it simply allows us to override what we need, to add behavior

An interceptor starting point
public class MyInterceptor : Interceptor
{
}

Interceptors in grpc-web

interceptors grpc-web-interceptors.png